package ltd.smallwang.infrastructure.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

  @ExceptionHandler(value = BizException.class)
  public Response bizException(BizException e) {
    log.error("", e);
    return Response.buildFailure(e.getErrCode(), e.getMessage());
  }

  @ExceptionHandler(value = NotLoginException.class)
  @ResponseStatus(HttpStatus.UNAUTHORIZED)
  public Response notLoginException(NotLoginException e) {
    log.error("", e);
    return Response.buildFailure(CommonErrorCode.NOT_LOGIN.getErrorCode(), "请登录后访问");
  }

  @ExceptionHandler(value = MethodArgumentNotValidException.class)
  public Response paramsValidException(MethodArgumentNotValidException exception) {
    log.error("", exception);
    return Response.buildFailure(exception.getTypeMessageCode(), exception.getLocalizedMessage());
  }

  @ExceptionHandler(value = Exception.class)
  public Response unknownException(Exception e) {
    log.error("", e);
    return Response.buildFailure(CommonErrorCode.SYSTEM_ERROR.getErrorCode(),
        CommonErrorCode.SYSTEM_ERROR.getErrorMessage());
  }
}
